package com.kindergarten.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kindergarten.pojo.Food;
import com.kindergarten.pojo.Notice;
import com.kindergarten.pojo.User;
import com.kindergarten.pojo.UserRole;
import com.kindergarten.service.IUserRoleService;
import com.kindergarten.service.IUserService;
import com.kindergarten.utils.DataResults;
import com.kindergarten.utils.ImportExcelUtils;
import com.kindergarten.utils.MMGridPageVoBean;
import com.kindergarten.utils.ResultCode;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author bruce
 * @since 2022-10-26
 */
@Controller
@RequestMapping("/user-api")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IUserRoleService userRoleService;

    /**
     * 跳转导入User页面
     *
     * @return
     */
    @RequestMapping("importUser")
    public String importUser() {
        return "importUser";
    }

    /**
     * 文件导入
     *
     * @return
     */
    @ResponseBody
    @PostMapping("importUserExcel")
    public DataResults importUserExcel(MultipartFile file) {
        try {
            int rowNum = 0;//已取值的行数
            int colNum = 0;//列号
            int realRowCount = 0;//真正有数据的行数
            //得到工作空间
            Workbook workbook = ImportExcelUtils.getWorkbookByInputStream(file.getInputStream(), file.getOriginalFilename());
            //得到工作表
            Sheet sheet = ImportExcelUtils.getSheetByWorkbook(workbook, 0);
            //根据需要是否加条数限制
            if (sheet.getRow(1000) != null) {
                //防止内存异常溢出
                throw new RuntimeException("系统已限制单批次导入必须小于或等于1000笔！");
            }
            //获取行数【实际行数】
            realRowCount = sheet.getPhysicalNumberOfRows();
            //需要添加的表，Project表实体类
            List<User> list = new ArrayList<User>();
            //处理表格数据
            for (Row row : sheet) {
                User user = new User();
                if (realRowCount == rowNum) {
                    //读取到头了，退出
                    break;
                }
                if (ImportExcelUtils.isBlankRow(row)) {//空行跳过
                    continue;
                }
                if (row.getRowNum() == -1) {
                    continue;
                } else {
                    //第一行表头跳过，标题行
                    if (row.getRowNum() == 0) {
                        continue;
                    }
                }
                rowNum++;
                colNum = 1;

                ImportExcelUtils.validCellValue(sheet, row, colNum, "序号");
                String id = ImportExcelUtils.getCellValue(sheet, row, colNum - 1);

                //验证Excel文件字段，这里根据表格内名称
                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "用户名");
                user.setUserName(ImportExcelUtils.getCellValue(sheet, row, colNum-1));

                //列号需要自加获取
                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "账户");
                user.setUserId(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "密码");
                user.setUserPassword(new BCryptPasswordEncoder().encode(ImportExcelUtils.getCellValue(sheet, row, colNum - 1)));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "部门");
                user.setDept(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "职位");
                user.setPosition(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "手机号");
                user.setUserTel(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "邮箱");
                user.setUserMail(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, " 性别");
                user.setUserSex("男".equals(ImportExcelUtils.getCellValue(sheet, row, colNum - 1)) ? 1 : 0);

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "生日");
                user.setUserBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(ImportExcelUtils.getCellValue(sheet, row, colNum - 1)));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "家庭住址");
                user.setUserAddress(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "身份证号码");
                user.setUserIdcard(ImportExcelUtils.getCellValue(sheet, row, colNum - 1));

                ImportExcelUtils.validCellValue(sheet, row, ++colNum, "用户类型");
                user.setUserState(Integer.valueOf(ImportExcelUtils.getCellValue(sheet, row, colNum - 1)));

                //省略重复表格列名数据处理~
                list.add(user);
            }
            System.out.println("=============================导入的项目数据完成===========================");
            //把集合中的数据新增到数据库表中[批量新增]
            userService.saveBatch(list);
            return DataResults.success(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResults.success(ResultCode.FAIL);
        }
    }

    /**
     * 01-跳转到模板引擎页面
     *
     * @return
     */
    @GetMapping("topage")
    public String topage() {
        return "user";  //模板引擎页面
    }

    /**
     * 02-数据加载分页
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("page")
    public MMGridPageVoBean page(User user) {
        MMGridPageVoBean pageVoBean = new MMGridPageVoBean();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.orderByDesc("account_create_time");
        queryWrapper.eq("del", 0); //删除不查询

        queryWrapper.like(user.getUserName() != null && !"".equals(user.getUserName()), "user_name", user.getUserName());
        queryWrapper.like(user.getUserId() != null && !"".equals(user.getUserId()), "user_id", user.getUserId());
        queryWrapper.eq(user.getUserSex() != null && user.getUserSex() != -1, "user_sex", user.getUserSex());
        queryWrapper.eq(user.getUserState() != null && user.getUserState() != -1, "user_state", user.getUserState());

        IPage<User> page = userService.page(new Page<User>(user.getPage(), user.getLimit()), queryWrapper);
        pageVoBean.setRows(page.getRecords()); //每页数据
        pageVoBean.setTotal(page.getTotal()); //总条数
        return pageVoBean;
    }


    /**
     * 02-数据加载分页
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllUserByRoleId")
    public MMGridPageVoBean getAllUserByRoleId(Integer roleId, @RequestParam(value = "page", defaultValue = "1") Integer page) {
        MMGridPageVoBean pageVoBean = new MMGridPageVoBean();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.orderByDesc("account_create_time");
        queryWrapper.eq("del", 0); //删除不查询

        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("role_id", roleId));
        List<String> userIds = new ArrayList<String>();
        for (UserRole userRole : userRoles) {
            userIds.add(userRole.getUserId());
        }
        if (userIds.size() == 0) {
            userIds.add("-1");
        }
        queryWrapper.in("user_id", userIds);
        IPage<User> pager = userService.page(new Page<User>(page, 10), queryWrapper);
        pageVoBean.setRows(pager.getRecords()); //每页数据
        pageVoBean.setTotal(pager.getTotal()); //总条数
        return pageVoBean;
    }


    /**
     * 02-查询没有角色用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllUserWithoutRole")
    public MMGridPageVoBean getAllUserWithoutRole(Integer roleId, User user) {
        MMGridPageVoBean pageVoBean = new MMGridPageVoBean();
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.orderByDesc("account_create_time");
        queryWrapper.eq("del", 0); //删除不查询

        //中间表
        List<UserRole> userRoles = userRoleService.list();
        List<String> userIds = new ArrayList<String>();
        for (UserRole userRole : userRoles) {
            userIds.add(userRole.getUserId());
        }
        if (userIds.size() == 0) {
            userIds.add("-1");
        }

        queryWrapper.notIn("user_id", userIds);

        IPage<User> pager = userService.page(new Page<User>(user.getPage(), user.getLimit()), queryWrapper);
        pageVoBean.setRows(pager.getRecords()); //每页数据
        pageVoBean.setTotal(pager.getTotal()); //总条数
        return pageVoBean;
    }

    /**
     * 02-跳转到模板引擎页面
     *
     * @return
     */
    @GetMapping("toaddpage")
    public String toaddpage() {
        return "userAdd";
    }

    /**
     * 检查用户名合法性
     *
     * @return
     */
    @ResponseBody
    @PostMapping("checkUserId")
    public DataResults checkUserId(String userId) {
        List<User> userList = userService.list(new QueryWrapper<User>().eq("user_id", userId).eq("del", 0));
        if (userList.size() > 0) {
            return DataResults.success(ResultCode.USERNAME_REPEAT); //9006
        } else {
            return DataResults.success(ResultCode.SUCCESS); //200
        }
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @PostMapping("add")
    public DataResults add(User user) {
        user.setUserPassword(new BCryptPasswordEncoder().encode(user.getUserPassword()));
        return DataResults.success(ResultCode.SUCCESS, userService.save(user));
    }

    /**
     * 02-跳转到模板引擎页面
     *
     * @return
     */
    @GetMapping("toupdatepage")
    public String toupdatepage(String userId, Model model) {
        //数据回显用的
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        model.addAttribute("userObject", user);
        return "userUpdate";  //模板引擎页面
    }

    /**
     * 更新
     *
     * @return
     */
    @ResponseBody
    @PutMapping("update")
    public DataResults update(User user) {
        user.setUserPassword(new BCryptPasswordEncoder().encode(user.getUserPassword()));
        System.out.println("要更新对象:" + user);
        return DataResults.success(ResultCode.SUCCESS, userService.updateById(user));
    }

    /**
     * 删除
     *
     * @return
     */
    @ResponseBody
    @DeleteMapping("delete/{id}")
    public DataResults delete(@PathVariable("id") String userId) {
        User user = new User();
        user.setUserId(userId);
        user.setDel(1);
        return DataResults.success(ResultCode.SUCCESS, userService.updateById(user));
    }

    /**
     * 检查原密码是否正确
     *
     * @param password
     * @return
     */
    @ResponseBody
    @PostMapping("checkUserPassword")
    public DataResults checkUserPassword(String password, HttpSession session) {
        User user = (User) session.getAttribute("user");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(password.toString(), user.getUserPassword())) {
            return DataResults.success(ResultCode.SUCCESS);
        } else {
            return DataResults.success(ResultCode.PASSWORD_ERROR); //原密码输入错误
        }
    }


    /**
     * 修改个人密码
     *
     * @param password
     * @return
     */
    @ResponseBody
    @PostMapping("updatePassword")
    public String updatePassword(String password, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            String encodePassword = new BCryptPasswordEncoder().encode(password);
            user.setUserPassword(encodePassword);
            userService.updateById(user);
            //session失效
            session.invalidate();
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "ERROR";
        }
    }

    @RequestMapping("editUserPage")
    public String editUserPage(String userId,Model model){
        User user = userService.getById(userId);
        model.addAttribute("manageUser",user);
        return "userEdit";
    }
}
